// routes/shops.js
const GROUP_NAME = 'shops';
const models = require("../models");
const {
  paginationDefine
} = require('../utils/router-helper');
const Joi = require('joi');
module.exports = [{
    method: 'GET',
    path: `/${GROUP_NAME}`,
    handler: async (request, reply) => {
      console.log(request.auth.credentials);
        const {
          rows: results,
          count: totalCount
        } = await models.shops.findAndCountAll({
          attributes: [
            'id',
            'name',
          ],
          limit: request.query.limit,
          offset: (request.query.page - 1) * request.query.limit,
        });
        let info = {
          code: '0',
          msg: 'ok'
        };
        // 开启分页的插件，返回的数据结构里，需要带上 result 与 totalCount 两个字段
        reply({
          results,
          totalCount,
          info
        });
      },
      config: {
        tags: ['api', GROUP_NAME],
        auth: false, //false 配置为不通过jwt验证
        description: '获取店铺列表',
        validate: {
          query: {
            ...paginationDefine
          }
        }
      },
  },
  {
    method: 'GET',
    path: `/${GROUP_NAME}/{shopId}/goods`,
    handler: async (request, reply) => {
        // 增加带有 where 的条件查询
        const {
          rows: results,
          count: totalCount
        } = await models.goods.findAndCountAll({
          // 基于 shop_id 的条件查询
          where: {
            shop_id: request.params.shopId,
          },
          attributes: [
            'id',
            'name',
          ],
          limit: request.query.limit,
          offset: (request.query.page - 1) * request.query.limit,
        });
        // 开启分页的插件，返回的数据结构里，需要带上 result 与 totalCount 两个字段
        reply({
          code: '0',
          msg: 'ok',
          results,
          totalCount
        });
      },
      config: {
        tags: ['api', GROUP_NAME],
        description: '获取店铺的商品列表',
        auth: false,
        description: '获取店铺列表',
        validate: {
          params: {
            shopId: Joi.string().description('商铺id'),
          },
          query: {
            ...paginationDefine
          }
        }
      },
  },
];